<template>
	<view>
        <u-popup  @open="openLogin" :show="loginPopupShow" mode="bottom" :round="10" @close="closeLogin" zIndex="999998">
            <view class="f__login">
                <view class="loginLoading" v-if="isLoading">
                    <u-loadmore status="loading" loadingText="正在登录..."></u-loadmore>
                </view>
                <view class="logo">
                  <image class="img" src="https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/202311/9e3836354a76be0f94e1892687b53e52.png" mode="aspectFill"></image>
                </view>
                <view class="title">欢迎登录~</view>
                <view class="text">会员用户登录后消费可享受折扣，享受更好的服务体验</view>
                <view class="loginButton" v-if="!isPhoneLogin">
                    <!-- #ifdef MP-WEIXIN -->
                    <button class="button" v-if="userInfo.token && userInfo.is_get_phone" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" :style="{background:PrimaryColor}">手机号</button><!-- 此功能需微信认证 -->
                    <button class="button marginT" v-if="!userInfo.token"  @click="onAuthorization" :style="{background:PrimaryColor}">登录</button>
                    <!-- #endif -->
                    <!-- #ifdef MP-ALIPAY -->
                    <button class="button" open-type="getAuthorize" scope="phoneNumber" @getAuthorize="decryptPhoneNumber" @error="onAuthError" :style="{background:PrimaryColor}">支付宝手机号登录</button><!-- 此功能需申请 -->
                    <button class="button marginT" open-type="getAuthorize" scope="userInfo" @getAuthorize="onAuthorization" :style="{background:PrimaryColor}">支付宝授权登录</button>
                    <!-- #endif -->
                    <button class="button" @click="closeLogin" style="background:#fff;margin-top:24rpx;" :style="{border:'2rpx solid '+PrimaryColor,color:PrimaryColor}">
                        暂不登录
                    </button>
                </view>
				
                <!-- 验证码登录 -->
                <view class="loginPhone" v-if="isPhoneLogin">
                    <view class="form-row">
                        <input class="input" type="number" v-model="phone" placeholder="请输入手机号码" placeholder-style="font-weight:normal;color:#bbbbbb;"></input>
                    </view>
                    <view class="form-row">
                        <input class="input" type="number" v-model="vCode" placeholder="请输入验证码" placeholder-style="font-weight:normal;color:#bbbbbb;"></input>
                        <view class="getvcode" :class="{forhidden:readonly}" @click="getVcode">{{ codeText }}</view>
                    </view>
                    <button class="submit" size="default" @click="onSubmit" :style="{background:PrimaryColor}">确定</button>
                </view>
                <!-- #ifdef MP -->
                <!-- 快速登录和手机号登录切换 -->
                <view class="tips">
                    <!-- <view @click="isPhoneLogin = !isPhoneLogin" class="goBuy" :style="{color:PrimaryColor}">{{isPhoneLogin?'快速登录':'手机号登录'}}</view> -->
                </view>
                <!-- #endif -->
            </view>
        </u-popup>
        
		
		<!-- 获取手机号授权 -->
		 <u-popup  @open="openPhone" :show="phonePopupShow" mode="bottom" :round="10" @close="closePhone" zIndex="999998">
			 <view class="f__login">
			     <view class="logo">
			       <image class="img" src="https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/202311/9e3836354a76be0f94e1892687b53e52.png" mode="aspectFill"></image>
			     </view>
			     <view class="title">获取手机号~</view>
			     <view class="loginButton" v-if="!isPhoneLogin">
			         <!-- #ifdef MP-WEIXIN -->
			         <button class="button" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" :style="{background:PrimaryColor}">手机号</button><!-- 此功能需微信认证 -->
			         <!-- #endif -->
			         <button class="button" @click="closePhone" style="background:#fff;margin-top:24rpx;" :style="{border:'2rpx solid '+PrimaryColor,color:PrimaryColor}">
			             暂不获取
			         </button>
			     </view>
			 </view>			 
		</u-popup>
		
		<!-- 如果是两个账号弹框 选择门店 -->
	<!-- 	<u-popup  @open="openStore" :show="storePopupShow" mode="bottom" :round="10" @close="closeStore" zIndex="999998">
			
		</u-popup> -->
		<u-modal :show="merge_data.is_merge" @confirm="merge_check_confirm" :showCancelButton="false" :asyncClose="true">
			<view class="slot-content">
				<view class="fontSize33">
					{{merge_data.msg}}
				</view>
				<view style="margin-top: 40rpx;">
					<u-radio-group
					    v-model="merge_data.merge_check_value"
					    placement="column"
						style=""
					  >
					 	<u-radio  
						:customStyle="{marginBottom: '10px'}"
						 v-for="(item, index) in merge_data.merge_check"
						  :key="index"
						  :label="merge_data.store_tong_flag? item.admin_name:item.store_name"
						  :name="item.custome_id" ></u-radio>
					  
					</u-radio-group>
				</view>
			</view>
		</u-modal>
		
	</view>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import {queryURLParams} from '@/plugins/utils.js';
// #ifdef MP
import { getPhoneInfo,getUserInfo } from './f-login.js';
// #endif
var clear;
export default {
    name: 'f-login',
    computed: {
    	...mapState(['loginPopupShow','phonePopupShow','userInfo']),
    },
	data() {
		return {
            // #ifndef MP-ALIPAY
            PrimaryColor: '#E1265D', //主题色
            // #endif
            // #ifdef MP-ALIPAY
            PrimaryColor: '#E1265D',
            // #endif
            // #ifdef APP-PLUS || H5
            isLoading:false,
            isPhoneLogin:true,//是否显示验证码登录
            // #endif
            // #ifndef APP-PLUS || H5
            isLoading:true,
            isPhoneLogin:false,//是否显示验证码登录
            // #endif
            readonly: false,
            codeText: '获取验证码',
            phone: '', //号码
            vCode: '', //验证码
            code: '',  //uni.login获取的code
			merge_data:{   //弹框
				merge_check:[   //合并门店列表
					// {
					// 	"custome_id": 528233,
					// 	"store_id": 208,
					// 	"store_name": "六零空间线上门店",
					// 	"admin_id": 3528,
					// 	"admin_name": "王力普"
					// },
					// {
					// 	"custome_id": 528242,
					// 	"store_id": 209,
					// 	"store_name": "六零空间线上门店",
					// 	"admin_id": 3528,
					// 	"admin_name": "王力普"
					// }
				], 
				is_merge:false,   //true显示合并的弹框
				ids:"528233,528242",          //提交时使用
				merge_check_value:528242,
				msg:"1212门钉",
				store_tong_flag:true
			},
			scene:{ming:222},
			getUserShow:true
		};
	},
    watch:{
        // #ifdef MP
			loginPopupShow(val){
				//静默登录
			   val && this.getLoginByUnion()
			},
			//手机号弹窗
			phonePopupShow(val){
				//静默登录
			
				val && this.getLoginByUnion()
			}
        // #endif
    },
	mounted(){
	
		var that = this
		
	},
	methods: {
		// 分享关系
		getBindingRelationship(id,share_uid){
			let param ={
				share_admin_id:id,
				share_uid:share_uid||''
			}
		this.$httpApi.getBindingRelationship(param).then(res => {
			
			// uni.showToast({
			// 	title: '绑定关系成功'+id,
			// 	icon: 'none'
			// });
		uni.removeStorageSync('share_admin_id')
		uni.removeStorageSync('share_uid')
			
		}).catch(err => {
					
		})
		},
        ...mapMutations(['setLoginPopupShow','setPhonePopupShow','setUserInfo']),
        //个人信息授权登录
        onAuthorization(e) {
			console.log(e);
            getUserInfo(info=>{
               
                let httpData = {
                    js_code: this.code,
                    nickname: info.nickName=="微信用户"?"":info.nickName, //昵称
                    avatar: info.avatarUrl || '', //头像
                    gender: info.gender || 0, //性别 0:未知 1:男 2:女
					...this.scene,
					...info,
                }
				
				
				
				
                 uni.$u.http.post('/api/auth/wechat/login', httpData,{custom:{isFactory:true}}).then(res => {
									 
                    let userInfo = {
                        ...info,
                        ...res, //token用于判断是否登录
                    }
                    this.setUserInfo(userInfo)
					
					
					//没有手机号
					this.closeLogin();
					// this.getUserOpen();
					if(res.is_get_phone){ 
						
						this.setPhonePopupShow(true);
					}
					
					
                    setTimeout(()=>{
						//获取个人信息
						 this.$httpApi.getUserIndex().then(res=>{
							 this.setUserInfo({...userInfo,...res})
						 })
                    },100)
                }).catch(res=>{
					this.getLoginByUnion(); //获取code
					
				})
            },err=>{
				console.log(err);
                 this.closeLogin();
            })
        },
        //授权手机号登录
        decryptPhoneNumber(e) {
		
			var codeLogin = this.code
            var that = this
            // #ifdef MP-WEIXIN
			if(e.detail.errMsg == 'getPhoneNumber:ok'){
						if(e.detail.iv){
							var phoneInfo = e.detail;
							
							//判断code是否存在
							//phoneInfo.code = that.code
						
							phoneInfo.code = e.detail.code
							if(!this.noEmpty(e.detail.code)){
								phoneInfo.code = codeLogin
							}
						
							// phoneInfo.admin_id = 3731
							// phoneInfo.store_id = 194
							
							 
							if(uni.getStorageSync('shareID')){
								let yuangong = JSON.parse(uni.getStorageSync('shareID'))
								phoneInfo.admin_id = yuangong.admin_id 
								phoneInfo.store_id = yuangong.store_id
								
							}
							//this.closeLogin();
							//请去getPhoneInfo方法中使用您的接口绑定信息
							
							getPhoneInfo({...phoneInfo,...that.scene }, r=>{
							console.log(r,'合并账户');
							    //合并账号
								if(r.is_merge&&r.merge_check[0].custome_id&&r.ids){
									let merge_check = r.merge_check
									this.merge_data = r;
									//默认第一个选中
									this.merge_data.merge_check_value = merge_check[0].custome_id
									//判断是否是同一个门店
									let store_tong_flag = false; //false 不是同一个门店
									if(merge_check.length==2){
										if(merge_check[0].store_id == merge_check[1].store_id){
											store_tong_flag = true
										}
									}
									this.merge_data.store_tong_flag = store_tong_flag
								}
								
								//关闭弹框
								this.closePhone();
								//获取个人资料
								let that = this
								setTimeout(()=>{
									
									let share_admin_id= uni.getStorageSync('share_admin_id')
									let share_uid=uni.getStorageSync('share_uid')
									if(share_admin_id||share_uid){
										that.getBindingRelationship(share_admin_id,share_uid)
									}
									//获取个人信息
									 that.$httpApi.getUserIndex().then(res=>{
										 res.exhibitionBox=true
										 that.setUserInfo({is_get_phone:false,token:that.userInfo.token,...res})
									 })
									 
									
								},100)						
							},err=>{
								this.getLoginByUnion(); //获取code
							})
						}else{
							// 授权失败请使用验证码登录
							// this.isPhoneLogin = true
							// uni.showToast({
							// 	title: '授权失败',
							// 	icon: 'none'
							// });
						}
			}else{
                 this.closeLogin()
            }
            // #endif
            
			// 阿里小程序
            // #ifdef MP-ALIPAY
            uni.getPhoneNumber({
                success:(res)=>{
                    //请去getPhoneInfo方法中使用您的接口绑定信息
                    getPhoneInfo(res.response, res=>{
                        let userInfo = {
                            // ...res,
                            token:true,//token用于判断是否登录
                        }
                        this.setUserInfo(userInfo)
                        setTimeout(()=>{
                            uni.showToast({
                                title: '登录成功1111',
                                icon: 'none'
                            });
                            that.closeLogin();
                        },100)
                    }, err=>{
                        // 授权失败请使用验证码登录
                        that.isPhoneLogin = true
                        uni.showToast({
                        	title: '授权登录失败,请使用手机号登录',
                        	icon: 'none'
                        });
                    });
                },
                fail:(res)=>{
                    // 授权失败请使用验证码登录
                    that.isPhoneLogin = true
                    uni.showToast({
                    	title: '授权登录失败,请使用手机号登录',
                    	icon: 'none'
                    });
                }
            })
            // #endif
		},
        // 支付宝拒绝
        onAuthError(e){
            uni.showToast({
            	title: '您已拒绝授权~',
            	icon: 'none'
            });
        },
		closeLogin(){
           
            this.setLoginPopupShow(false);
            // #ifdef APP-PLUS || H5
            this.isLoading = false
            this.isPhoneLogin = true//是否显示验证码登录
            // #endif
            // #ifndef APP-PLUS || H5
            this.isLoading = true
            this.isPhoneLogin = false//是否显示验证码登录
            // #endif
		},
		//手机号弹窗关闭
		closePhone(){
		   
		    this.setPhonePopupShow(false);
		},
		//打开弹框
		openLogin(){
			// #ifdef MP
			 // #endif
		},
		//打开手机号弹框
		openPhone(){
			// #ifdef MP
			 // #endif
		},
        // 自动静默登录----获取code
        // 静默登录：就是已经登录过的用户，被迫下线。调用此接口快速登录
        getLoginByUnion(){
           
			 var that = this
			
			//二维码参数
			// uni.getStorage({
			//     key:'scene',
			//     success: (e) => {
			
			//         that.scene = queryURLParams(e.data)
			//     },
			// 	fail:(e)=>{
			// 	}
			// })
			
			try {
			   let value = uni.getStorageSync('scene')
			  if (value) {
			       that.scene = queryURLParams(value)
			  }
			} catch (e) {
			  // Do something when catch error
			}
            uni.login({
                success(res){
                 
                    that.code = res.code
                    let httpData = {
                        code: res.code,
                    }
                    // uni.$u.http.post('您的接口', httpData).then(res => {
                        setTimeout(()=>{
                            // 自动静默登录失败--打开手动登录
                            that.isLoading = false
                        },500)
                    // }).catch(()=>{
                    //     // 自动静默登录失败--打开手动登录
                    //     that.isLoading = false
                    // })
                }
            })
        },
        //验证码按钮文字状态
        getCodeState() {
        	const _this = this;
        	this.readonly = true;
        	this.codeText = '60S后重新获取';
        	var s = 60;
        	clear = setInterval(() => {
        		s--;
        		_this.codeText = s + 'S后重新获取';
        		if (s <= 0) {
        			clearInterval(clear);
        			_this.codeText = '获取验证码';
        			_this.readonly = false;
        		}
        	}, 1000);
        },
        //获取验证码
        getVcode(){
          
        	if (this.readonly) {
                uni.showToast({
                	title: '验证码已发送~',
                	icon: 'none'
                });
        		return;
        	}
        	if (this.phone == '') {
                uni.showToast({
                	title: '请输入手机号~',
                	icon: 'none'
                });
        		return;
        	}
            const phoneRegular = /^1\d{10}$/;
        	if (!phoneRegular.test(this.phone)) {
                uni.showToast({
                	title: '手机号格式不正确~',
                	icon: 'none'
                });
        		return;
        	}
            let httpData = {}
            // 获取验证码接口
            // uni.$u.http.post('您的接口', httpData).then(res => {
                this.getCodeState(); //开始倒计时
            // })
        },
        // 手机号登录
        onSubmit() {
        	if (this.phone == '') {
                uni.showToast({
                	title: '请输入手机号~',
                	icon: 'none'
                });
        		return;
        	}
            const phoneRegular = /^1\d{10}$/;
        	if (!phoneRegular.test(this.phone)) {
                uni.showToast({
                	title: '手机号格式不正确~',
                	icon: 'none'
                });
        		return;
        	}
        	if (this.vCode == '') {
                uni.showToast({
                	title: '请输入验证码~',
                	icon: 'none'
                });
        		return;
        	}
        	let httpData = {};
        	// uni.$u.http.post('您的接口',httpData).then(res => {
                uni.showToast({
                	title: '登录成功~',
                	icon: 'none'
                });
            // });
        },
        
		//弹框确认
        async merge_check_confirm(){
			let param = {
				ids: this.merge_data.ids,
				checked: this.merge_data.merge_check_value
			}
			
				await this.$httpApi.postAuthMerge(param).then(res=>{
					this.merge_data.is_merge = false
				})
			
		
			await this.$httpApi.getUserIndex().then(res=>{
			   this.setUserInfo({is_get_phone:false,token:this.userInfo.token,...res})
			})
		},
		
		
		
        
        
        
        
        
	}
};
</script>

<style lang="scss" scoped>
	
	.avatar{
	    width: 80rpx;
	    height: 80rpx;
	    border-radius: 40rpx;
	    margin-right: 10rpx;
	}
	.title {
	    font-size: 30rpx;
	    color: #333;
	}
.f__login {
    padding: 48rpx 32rpx;
    border-radius: 18rpx 18rpx 0 0;
    z-index: 99;
    position: relative;
    .loginLoading {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(255, 255, 255, .95);
        z-index: 999;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }
    .logo {
        width: 90rpx;
        height: 90rpx;
        border-radius: 18rpx;
        overflow: hidden;
        .img {
            width: 90rpx;
            height: 90rpx;
			border-radius: 45rpx;
        }
    }
    .title {
        font-size: 40rpx;
        font-weight: bold;
        margin-top: 24rpx;
    }
    .text {
        font-size: 24rpx;
        color: #666;
        margin-top: 16rpx;
    }
    .loginButton {
        margin-top: 56rpx;
        .button {
            color: #fff;
            width: 100%;
            height: 92rpx;
        }
        .marginT{
            margin-top: 24rpx;
        }
    }
    .tips {
        margin-top: 24rpx;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        .left {
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
        }
        .goBuy {
            font-size: 24rpx;
            /* margin-left: 16rpx; */
            background: none;
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
            justify-content: flex-start;
            padding: 0;
            margin: 0;
            color: #1fba1a;
        }
    }
}
.loginPhone{
    .form-row {
        position: relative;
        border-bottom: 1rpx solid #e8e8e8;
        line-height: 1;
        margin-top: 24rpx;
        .input{
            font-size: 34rpx;
            line-height: 102rpx;
            height: 94rpx;
            width: 100%;
            box-sizing: border-box;
            font-size: 30rpx;
            padding: 0;
            font-weight: bold;
        }
        .getvcode {
            font-size: 26rpx;
            height: 80rpx;
            color: #333;
            line-height: 80rpx;
            background: #eee;
            min-width: 188rpx;
            text-align: center;
            border-radius: 8rpx;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: 0;
            z-index: 11;
            &.forhidden {
                background: #eee;
                color: #cccccc;
            }
        }
    }
    .submit{
        margin-top: 60rpx;
        color: #fff;
        width: 100%;
        border: none;
    }
}
</style>
